/* eslint-disable no-empty */
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from "vue";
import App from "./App";
import router from "./router";
import store from "./store";
import iView from "iview";
import crypto from "crypto";
import JQ from "jquery";
import VueWorker from "vue-worker";
import VueQriously from "vue-qriously";
import "iview/dist/styles/iview.css";
import Viewer from "v-viewer";
import "viewerjs/dist/viewer.css";
import VueCropper from "vue-cropper";
import VueLazyload from "vue-lazyload"; //懒加载
import VueVideoPlayer from "vue-video-player";
import VueClipboard from "vue-clipboard2"; // 粘贴板
import axios from "axios";
import utilJs from "./assets/util";
import {
  keyPair,
  ws_encrypt,
  axios_encrypt,
  ws_decode
} from "./assets/encrypt/encrypt.js";
import PinyinMatch from "pinyin-match"; // 简体中文拼音匹配插件
Vue.prototype.$pinyinMatch = PinyinMatch;
Vue.prototype.$axios_encrypt = axios_encrypt;
Vue.prototype.$ws_decode = ws_decode;
Vue.prototype.$ws_decode = ws_decode;
import "../static/css/index.less";
import "../static/image/iconfont.css";
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import { message } from "./assets/message";
import {
  imessage_error,
  imessage_info,
  imessage_loading,
  imessage_success,
  imessage_warning
} from "./assets/imessage";
require("video.js/dist/video-js.css");
require("vue-video-player/src/custom-theme.css");
Vue.prototype.$axios = axios;
Vue.prototype.$message = message;
iView.Message.warning = imessage_warning;
iView.Message.error = imessage_error;
iView.Message.info = imessage_info;
iView.Message.loading = imessage_loading;
iView.Message.success = imessage_success;
// import VuePreview from 'vue-preview'
// Vue.use(VuePreview)
Vue.use(VueVideoPlayer);
Vue.use(VueLazyload, {
  preLoad: 1.0,
  error: "static/image/home/errDefault.png"
});
Vue.use(ElementUI);
Vue.use(VueClipboard);
Vue.use(VueCropper);
Vue.use(Viewer);
Viewer.setDefaults({
  filter(image) {
    let src = image.getAttribute("viewer");
    let srcPath = image.getAttribute("src") || "a";
    return src == "true" &&
      srcPath.indexOf("yH5BAEAAAAALAAAAAABAAEAAAIBRAA7") == -1
      ? image
      : null;
  },
  zIndexInline: 9999,
  button: true,
  navbar: true,
  title: true,
  toolbar: true,
  tooltip: true,
  movable: true,
  zoomable: true,
  rotatable: true,
  scalable: true,
  transition: true,
  fullscreen: true,
  keyboard: true,
  url: "data-source"
});
Vue.use(iView);
Vue.use(VueQriously);
Vue.use(VueWorker);

Vue.prototype.$utilJs = utilJs;

Vue.prototype.$publicKey = function(key, action, method) {
  return JSON.stringify({
    head: {
      key: key,
      name: "",
      action: action,
      method: method,
      version: "1",
      time: new Date().getTime()
    },
    body: {
      clientPublicKey: keyPair.publicKey
    }
  });
};
//获取二维码、登录信息
Vue.prototype.$loginJsonString = function(key, action, method, body) {
  console.log("执行1111");
  let obj = {
    head: {
      key: key,
      name: "",
      action: action,
      method: method,
      version: "1",
      time: new Date().getTime()
    },
    body: body
  };
  if (
    method == "1.1.0001" ||
    method == "1.1.0002" ||
    method == "1.1.0049" ||
    method == "1.3.1001"
  ) {
    obj = ws_encrypt(obj);
    console.log(obj, action, method, "ws加密");
  }
  return JSON.stringify(obj);
};
//已读未读报文发送
Vue.prototype.$publicSend = function(key, action, method, body) {
  // 写入日志
  let bodyJson = JSON.stringify(body);
  let args = JSON.stringify({
    type: "SEND",
    socketUrl: `${action}/${method}`,
    args: `userid: [${
      store.state.myInfo.id
    }], key: [${key}], body: [${bodyJson}]`
  });
  this.$shell("SaveLog", [args]);
  let obj = {
    head: {
      key: key,
      name: "",
      action: action,
      method: method,
      version: "1",
      time: new Date().getTime()
    },
    body: body
  };
  // if(action == '1.100' && (method == '1.1.0049' || method == '1.1.1004')){
  if (method == "1.1.0049" || method == "1.1.1004") {
    obj = ws_encrypt(obj);
    console.log(obj, action, method, "ws加密");
  }
  return JSON.stringify(obj);
};

//发送广播报文
Vue.prototype.$radioMessage = function(key, action, method, body, time) {
  return JSON.stringify({
    head: {
      key: key,
      name: "",
      action: action,
      method: method,
      version: "1",
      time: time
    },
    body: body
  });
};
//报文body拼接
Vue.prototype.$socketBody = function(obj, type, toValue, time) {
  return Object.assign(obj, {
    content: {
      font: store.state.fontSetting,
      sections: [
        {
          items: [
            {
              type: type,
              value: toValue,
              messageId: toValue.messageId,
              title: obj.title
            }
          ]
        }
      ],
      timestamp: time
    }
  });
};

//zk118新增，关键字特殊字体颜色(注意：暂未处理正则需要转义的字符),127修改，按下标进行颜色设置，不再使用replace,针对多关键字匹配到颜色标签里的内容
Vue.prototype.$setKeyWords = function(str, keywords, color, len = 0) {
  //第一个是原字符串，第二个是关键字(数组类型)，第三个是需要设置的颜色
  // let str1 = str;
  // for(let i in keywords){
  //   let reg = new RegExp(keywords[i],"ig")
  //   str1 = str1.replace(reg,`<span style="color:${color}">${keywords[i]}</span>`)
  // }
  if (keywords.length == 0) {
    return;
  }
  let obj = {}; //属性名为关键字，属性值为关键字出现的下标
  for (let i in keywords) {
    let idsList = [];
    idsList = this.$getAllIndex(str, keywords[i]);
    obj[keywords[i]] = idsList;
  }
  let orderList = [];
  for (let i in obj) {
    orderList = orderList.concat(obj[i]);
  }
  orderList = orderList.sort((a, b) => {
    return b - a;
  });
  let str1 = "";
  if (len && len < str.length) {
    str1 = str.substring(0, len) + "......";
    str1 = str1.split("");
  } else {
    str1 = str.split(""); //str拆成数组
  }
  for (let m in orderList) {
    for (let n in obj) {
      if (obj[n].indexOf(orderList[m]) != -1) {
        str1.splice(
          orderList[m],
          n.length,
          `<span style="color:${color};display:inline-block;">${n}</span>`
        );
      }
    }
  }
  str1 = str1.join("");
  return str1;
};
//综合搜索高亮显示
// Vue.prototype.$replaceKeyWords = function (str, keyword, color, len = 0) {
//   let key = `<span style="color:${color};display:inline-block;">${keyword}</span>`
//   let num = Math.ceil((len - keyword.length) / 2)
//   let str1 = ''
//   let str2 = ''
//   let index = str.indexOf(keyword)
//   if(len == 0){
//     if(keyword == ''){
//       return str
//     }
//     return str2 = str.replace(new RegExp(keyword, "gi"), key)
//   }
//   if (index - num < 0) {
//     if (keyword.length + 2 * num > str.length - 1) {
//       str1 = str.slice(0, str.length)
//     } else {
//       str1 = str.slice(0, keyword.length + 2 * num)
//     }
//   } else if (index + keyword.length + num - str.length > 0) {
//     if(str.length - 2 * num - keyword.length <0){
//       str1 = str.slice(0, str.length)
//     }else{
//       str1 = str.slice(str.length - 2 * num - keyword.length, str.length)
//     }
//   } else {
//     str1 = str.slice(index - num, index + keyword.length + num)
//   }
//   str1 = str1.replace(new RegExp("<br>", "g"),'')
//   str2 = str1.replace(new RegExp(keyword, "gi"), key)
//   if (str2 == '') {
//     str2 = str.slice(0, len)
//   }
//   if(keyword == ''){
//     str2 = str.replace(new RegExp("<br>", "g"),'').slice(0, len)
//   }
//   if (len && len < str.length) {
//     str2 = str2 + "......"
//   }
//   return str2
// }

//综合搜索高亮显示
Vue.prototype.$replaceKeyWords = function(str, keyword, color, len = 0) {
  let num = Math.ceil((len - keyword.length) / 2);
  let str1 = "";
  let str2 = "";
  let index = str.toLowerCase().indexOf(keyword.toLowerCase());
  let exec1 = new RegExp(keyword, "gi").exec(str);
  let key = `<span style="color:${color};display:inline-block;">${
    exec1 ? exec1[0] : keyword
  }</span>`;

  if (len == 0) {
    if (keyword == "") {
      return str;
    } else if (exec1) {
      return (str2 = str.replace(new RegExp(exec1[0], "g"), key));
    } else {
      return (str2 = str.replace(new RegExp(keyword, "g"), key));
    }
  }
  if (index - num < 0) {
    if (keyword.length + 2 * num > str.length - 1) {
      str1 = str.slice(0, str.length);
    } else {
      str1 = str.slice(0, keyword.length + 2 * num);
    }
  } else if (index + keyword.length + num - str.length > 0) {
    if (str.length - 2 * num - keyword.length < 0) {
      str1 = str.slice(0, str.length);
    } else {
      str1 = str.slice(str.length - 2 * num - keyword.length, str.length);
    }
  } else {
    str1 = str.slice(index - num, index + keyword.length + num);
  }
  str1 = str1.replace(new RegExp("<br>", "g"), "");
  if (exec1) {
    str2 = str1.replace(new RegExp(exec1[0], "g"), key);
  } else {
    str2 = str1.replace(new RegExp(keyword, "g"), key);
  }
  if (str2 == "") {
    str2 = str.slice(0, len);
  }
  if (len && len < str.length) {
    str2 = str2 + "......";
  }
  return str2;
};
// zk127新增,获取某字符(串)在其他字符串中所有的下标
Vue.prototype.$getAllIndex = function(rawStr, str) {
  let tempValue = rawStr;
  var indexList = [];
  let count = tempValue.length;
  for (var index = 0; index < count; index++) {
    if (tempValue.indexOf(str) != -1) {
      let aa = tempValue.indexOf(str);
      aa += index * str.length;
      tempValue = tempValue.replace(str, "");
      indexList.push(aa);
    }
  }
  return indexList;
};
//发送消息报文
Vue.prototype.$sendMsg = function(toInfo, key, type, value) {
  let isGroup = toInfo.isGroup == "1" ? true : false;
  let methodValue = isGroup ? "1.1.2001" : "1.1.1001";
  let sql = isGroup
    ? `message_list_${store.state.myInfo.id}`
    : `private_list_${store.state.myInfo.id}`;
  let nowTime = new Date().getTime();
  let toValue = {
    sendName: store.state.myInfo.name,
    receiveName: toInfo.name
  };
  toValue = JSON.stringify(Object.assign(toValue, value));
  let bodyObject = isGroup
    ? {
        messageKey: key,
        groupId: toInfo.id,
        userId: store.state.myInfo.id
      }
    : {
        messageKey: key,
        sendUserId: store.state.myInfo.id,
        receiveUserId: toInfo.id,
        isServiceAcc: store.state.isService ? 1 : 0
      };
  bodyObject = this.$socketBody(bodyObject, type, toValue, nowTime);
  let obj = {
    head: {
      key: key,
      name: "",
      action: "1.500",
      method: methodValue,
      version: "1",
      time: nowTime
    },
    body: bodyObject
  };
  obj = ws_encrypt(obj);
  console.log(obj, 1.5, methodValue, "ws加密");
  // 写入日志
  let toInfoJson = JSON.stringify(toInfo);
  let valueJson = JSON.stringify(toInfo);
  let args = JSON.stringify({
    type: "SEND",
    socketUrl: `${obj.head.action}/${methodValue}`,
    args: `userid: [${
      store.state.myInfo.id
    }], toInfo:[${toInfoJson}], key: [${key}], type: [${type}], value: [${valueJson}]`
  });
  this.$shell("SaveLog", [args]);
  //新增 消息发送5s后无返回，判定为发送消息失败
  setTimeout(() => {
    // 查询当前消息状态是否为1
    let msgType = JSON.parse(
      this.$shellSQL(
        JSON.stringify({
          Sqlstr: `SELECT isSuccessSend FROM ${sql} WHERE messageId = '${key}'`
        }),
        1
      )
    );
    let msgTime = JSON.parse(
      this.$shellSQL(
        JSON.stringify({
          Sqlstr: `SELECT time  FROM ${sql} WHERE messageId = '${key}'`
        }),
        1
      )
    );
    JSON.parse(
      this.$shellSQL(
        JSON.stringify({
          Sqlstr: `UPDATE ${sql} SET isSuccessSend = '2' WHERE time < ${
            msgTime.list[0].time
          } AND isSuccessSend = '1'`
        })
      )
    );
    if (msgType.list[0].isSuccessSend == 1) {
      JSON.parse(
        this.$shellSQL(
          JSON.stringify({
            Sqlstr: `UPDATE ${sql} SET isSuccessSend = '2' WHERE messageId = '${key}'`
          })
        )
      );
      store.commit("setOvertimeMsgKey", key);
    }
  }, 10000);
  return JSON.stringify(obj);
};

Vue.prototype.$wsSendMsg = function(toInfo, key, type, value, ws) {
  if (ws) {
    ws.send(Vue.prototype.$sendMsg(toInfo, key, type, value));
  } else {
    Vue.prototype.$sendMsg(toInfo, key, type, value);
  }
};
Vue.prototype.$receiveMsg = function(info) {
  console.log(info);
};

Vue.prototype.$setSendStatus = function(info) {
  console.log(info);
};

Vue.prototype.$getOffline = function() {
  console.log("离线报文");
  store.state.ws.send(
    this.$loginJsonString(this.$func.uuid(), "1.500", "1.3.1001", {
      content: {
        font: store.state.fontSetting,
        sections: [
          {
            items: [
              {
                type: "",
                value: ""
              }
            ]
          }
        ],
        timestamp: new Date().getTime()
      },
      userId: store.state.myInfo.id,
      farBack: "1"
    })
  );
};

Vue.prototype.$downLoad = function(url, data, success, error) {
  var requrl = store.state.url + url + "?id=" + data;
  var xhr = new XMLHttpRequest();
  xhr.open("GET", requrl, true); // 也可以使用POST方式，根据接口
  xhr.responseType = "blob"; // 返回类型blob
  const token = window.localStorage.getItem("httpToken");
  xhr.setRequestHeader("httptoken", "token");
  // 定义请求完成的处理函数，请求前也可以增加加载框/禁用下载按钮逻辑
  xhr.onload = function() {
    // 请求完成
    if (this.status === 200) {
      // 返回200
      console.log("this.response", this.response);
      var blob = this.response;
      console.log(blob, "zk1214下载接口返回");
      success(blob);
    } else {
      error();
    }
  };
  xhr.send();
  // 写入日志
  let dataJson = JSON.stringify(data);
  let args = JSON.stringify({
    type: "SEND(http)",
    Url: `${url}`,
    args: `userid: [${store.state.myInfo.id}], body:[${dataJson}]`
  });
  this.$shell("SaveLog", [args]);
};

// 处理分享文件下载ID
Vue.prototype.$downLoadFile = function(url) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, true); // 也可以使用POST方式，根据接口
  xhr.responseType = "blob"; // 返回类型blob
  const token = window.localStorage.getItem("httpToken");
  xhr.setRequestHeader("httptoken", token);
  // 定义请求完成的处理函数，请求前也可以增加加载框/禁用下载按钮逻辑
  xhr.onload = function() {
    // 请求完成
    if (this.status === 200) {
      // 返回200
      console.log("this.response", this.response);
      var blob = this.response;
      success(blob);
    } else {
      error();
    }
  };
  xhr.send();
};

Vue.prototype.$upload = function(url, data, success, error) {
  const token = window.localStorage.getItem("httpToken");
  JQ.ajax({
    type: "POST",
    url: store.state.url + url,
    dataType: "json",
    async: true,
    processData: false, // 告诉jQuery不要去处理发送的数据
    contentType: false,
    xhrFields: {
      withCredentials: true
    },
    headers: {
      httptoken: `${token}`
    },
    // beforeSend: function(request) {
    //   request.setRequestHeader("Authorization", localStorage.getItem("access_token"));
    // },
    data: data,
    success: success,
    error: error
  });
  // 写入日志
  let dataJson = JSON.stringify(data);
  let args = JSON.stringify({
    type: "SEND(http)",
    Url: `${url}`,
    args: `userid: [${store.state.myInfo.id}], body:[${dataJson}]`
  });
  this.$shell("SaveLog", [args]);
};

//jsonp、ajax请求，参数请求地址、参数、成功回调、失败回调
Vue.prototype.$ajax = function(url, data, success, error) {
  const token = window.localStorage.getItem("httpToken");
  JQ.ajax({
    type: "POST",
    url: store.state.url + url,
    dataType: "json",
    xhrFields: {
      withCredentials: true
    },
    headers: {
      httptoken: `${token}`
    },
    // beforeSend: function(request) {
    //   request.setRequestHeader("Authorization", localStorage.getItem("access_token"));
    // },
    data: data,
    success: success,
    error: error
  });
  // 写入日志
  let dataJson = JSON.stringify(data);
  let args = JSON.stringify({
    type: "SEND(http)",
    Url: `${url}`,
    args: `userid: [${store.state.myInfo.id}], body:[${dataJson}]`
  });
  this.$shell("SaveLog", [args]);
};

Vue.prototype.$Checkajax = function(url, data, success, error) {
  const token = window.localStorage.getItem("httpToken");
  JQ.ajax({
    type: "POST",
    url: url,
    dataType: "json",
    xhrFields: {
      withCredentials: true
    },
    headers: {
      httptoken: `${token}`
    },
    // beforeSend: function(request) {
    //   request.setRequestHeader("Authorization", localStorage.getItem("access_token"));
    // },
    data: data,
    success: success,
    error: error
  });

  // 写入日志
  let dataJson = JSON.stringify(data);
  let args = JSON.stringify({
    type: "SEND(http)",
    Url: `${url}`,
    args: `userid: [${store.state.myInfo.id}], body:[${dataJson}]`
  });
  this.$shell("SaveLog", [args]);
};

Vue.prototype.$ajaxget = function(url, data, success, error) {
  const token = window.localStorage.getItem("httpToken");
  JQ.ajax({
    type: "get",
    url: store.state.url + url,
    dataType: "json",
    xhrFields: {
      withCredentials: true
    },
    headers: {
      httptoken: `${token}`
    },
    // beforeSend: function(request) {
    //   request.setRequestHeader("Authorization", localStorage.getItem("access_token"));
    // },
    data: data,
    success: success,
    error: error
  });

  // 写入日志
  let dataJson = JSON.stringify(data);
  let args = JSON.stringify({
    type: "SEND(http)",
    Url: `${url}`,
    args: `userid: [${store.state.myInfo.id}], body: [${dataJson}]`
  });
  this.$shell("SaveLog", [args]);
};

// 请求公文接口登录
Vue.prototype.$ajax_official_login = function(type, url, data, success, error) {
  JQ.ajax({
    type: type,
    url: store.state.url_official + url,
    dataType: "json",
    xhrFields: {
      withCredentials: true
    },
    // beforeSend: function(request) {
    //   request.setRequestHeader("Authorization", localStorage.getItem("access_token"));
    // },
    data: data,
    success: success,
    error: error
  });
};

Vue.prototype.$getOfficialToken = function(info) {
  vm.$ajax_official_login(
    "post",
    "message/login",
    {
      username: info.id,
      password: "******"
    },
    res => {
      if (res.code == 200) {
        vm.$store.commit("setTokenOff", res.token);
      } else {
        vm.$Message.warning("公文message/login：" + res.msg);
      }
    },
    res => {
      vm.$Message.warning("公文message/login：" + res.msg);
    }
  );
};

// 请求公文接口上传
Vue.prototype.$ajax_official_update = function(
  type,
  url,
  data,
  success,
  error
) {
  console.log(data, "datadatadatadata");
  let newData = new FormData();
  newData.append("file", data.raw);
  newData.append("fileName", data.name);
  newData.append("uid", data.uid);
  if (data.oId) newData.append("oId", data.oId);
  if (data.fillId) newData.append("fillId", data.fillId);
  JQ.ajax({
    type: type,
    url: store.state.url_official + url,
    dataType: "json",
    processData: false, // 告诉jQuery不要去处理发送的数据
    contentType: false,
    headers: {
      Authorization: `Bearer ${store.state.token_official}`
    },
    // beforeSend: function(request) {
    //   request.setRequestHeader("Authorization", localStorage.getItem("access_token"));
    // },
    data: newData,
    success: success,
    error: error
  });
};

// 请求公文接口json
Vue.prototype.$ajax_official_JSON = function(type, url, data, success, error) {
  JQ.ajax({
    type: type,
    url: store.state.url_official + url,
    xhrFields: {
      withCredentials: true
    },
    headers: {
      "Content-Type": "application/json",
      "X-Requested-With": "XMLHttpRequest",
      Authorization: `Bearer ${store.state.token_official}`
    },
    // beforeSend: function(request) {
    //   request.setRequestHeader("Authorization", localStorage.getItem("access_token"));
    // },
    data: data,
    success: success,
    error: error
  });
};

// 请求公文接口
Vue.prototype.$ajax_official = function(type, url, data, success, error) {
  JQ.ajax({
    type: type,
    url: store.state.url_official + url,
    // dataType: "json",
    xhrFields: {
      withCredentials: true
    },
    headers: {
      Authorization: `Bearer ${store.state.token_official}`
    },
    // beforeSend: function(request) {
    //   request.setRequestHeader("Authorization", localStorage.getItem("access_token"));
    // },
    data: data,
    success: success,
    error: error
  });
};

// 导出Excel 附件 文件下载
(Vue.prototype.$downLoadFiles = function(url, fileNames) {
  axios
    .get(`${store.state.url_official}${url}`, {
      responseType: "blob",
      headers: {
        Authorization: `Bearer ${store.state.token_official}`
      },
      onDownloadProgress: evt => {
        console.log(
          "progressEvent==>",
          parseInt((evt.loaded / evt.total) * 100)
        );
        // 对原生进度事件的处理
      }
    })
    .then(res => {
      if (res.status === 200) {
        if (res.headers.code != 500) {
          let fileName = null;
          if (!fileNames) {
            const disposition = res.headers["content-disposition"];
            fileName = disposition.substring(
              disposition.indexOf("filename=") + 9,
              disposition.length
            );
          }
          let url = window.URL.createObjectURL(new Blob([res.data]));
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute(
            "download",
            decodeURIComponent(fileNames ? fileNames : fileName)
          );
          document.body.appendChild(link);
          link.click();
        } else {
          vm.$Message.warning({
            message: decodeURIComponent(res.headers.msg),
            type: "warning"
          });
        }
      }
    });
}),
  //外壳接口封装fun
  (Vue.prototype.$shell = function(methodsName, params) {
    console.log(
      methodsName,
      params,
      "调用当前.net方法、参数",
      new Date().getTime()
    );
    let result = window.external.InvokeWinFormMethod(
      "Internal.Function",
      methodsName,
      ...params
    );
    return result;
  });

// 中间件插件，params规定格式为[插件名字，类名，方法，参数，类型（默认为空）]
// params例如["UMP_Plugin_ICReadDrive","MethodList","Open",[],""]
Vue.prototype.$downloadPlug = function(methodsName, params) {
  console.log(methodsName, params, "调用当前.net方法、参数");
  let result = window.external.InvokeWinFormMethod(
    "UMP.Plugin.Middle",
    methodsName,
    ...params
  );
  return result;
};
//  2022/4/11 zc新增  获取软件信息采集
Vue.prototype.$softWareInformation = function(methodsName, params) {
  console.log(methodsName, params, "调用当前.net方法、参数");
  let result = window.external.InvokeWinFormMethod(
    "UMP.Plugin.SoftInfo",
    methodsName,
    ...params
  );
  return result;
};

// 2022/4/15 zc新增 IC卡读取插件
Vue.prototype.$icReadDrive = function(methodsName) {
  console.log(methodsName, "调用当前.net方法、参数");
  let result = window.external.InvokeWinFormMethod(
    "UMP.Plugin.ICReadDrive",
    methodsName
  );
  return result;
};

Vue.prototype.$getAddress = function(methodsName, params) {
  let result = window.external.InvokeWinFormMethod(
    "UMP.Plugin.Address",
    methodsName,
    ...params
  );
  return result;
};

Vue.prototype.$ShareScreenAssistance = function(methodsName, params) {
  console.log(methodsName, params, "调用当前.net方法、参数");
  let result = window.external.InvokeWinFormMethod(
    "UMP.Plugin.ShareScreenAssistance",
    methodsName,
    ...params
  );
  return result;
};

//同屏连接
Vue.prototype.$shareScreenConnect = function(methodsName, params) {
  let screenInfo = Vue.prototype.$ShareScreenAssistance(
    "ConnectShareScreenServer",
    [
      `${store.state.myInfo.id}_PC`,
      store.state.myInfo.name,
      store.state.myInfo.headImage,
      store.state.myInfo.gender.toString()
    ]
  );
  screenInfo = JSON.parse(screenInfo);
  // console.log('注册同屏信息',screenInfo)
  if (screenInfo.return_code === "TRUE") {
    store.state.connectShareScreenServer = true;
  }
};

//远程控制
Vue.prototype.$remoteControl = function(methodsName, params) {
  console.log(methodsName, params, "调用当前.net方法$remoteControl、参数");
  let result = window.external.InvokeWinFormMethod(
    "UMP.Plugin.RemoteAssistance",
    methodsName,
    ...params
  );
  return result;
};

//远程连接
Vue.prototype.$remoteControlConnect = function(methodsName, params) {
  //注册远程,zk0301增加参数 this.myInfo.name, this.myInfo.headImage, this.myInfo.gender.toString(),0303修改，加XL
  let remoteInfo = Vue.prototype.$remoteControl("ConnectRemoteServer", [
    store.state.myInfo.id,
    store.state.myInfo.name,
    store.state.myInfo.headImage,
    store.state.myInfo.gender.toString()
  ]);
  remoteInfo = JSON.parse(remoteInfo);
  console.log("注册远程信息", remoteInfo);
  if (remoteInfo.return_code === "TRUE") {
    store.state.connectRemoteServer = true;
  }
};

//代理服务
Vue.prototype.$proxy = function(methodsName, params) {
  let result = window.external.InvokeWinFormMethod(
    "UMP.Plugin.Proxy",
    methodsName,
    ...params
  );
  return result;
};

//消息回执
Vue.prototype.$getMes = function(myId, mesId) {
  this.ws.send(
    this.$publicSend(mesId, "1.500", "1.1.1111", {
      userId: myId,
      messageId: mesId
    })
  );
};

Vue.prototype.$shellSQL = function(params, next) {
  let result = "";
  try {
    let param = arguments[1] ? "SearchBySqlstr" : "OperatingBySqlstr";
    result = window.external.InvokeWinFormMethod(
      "UMP.Plugin.SqlLiteOpera",
      "SqlListData",
      store.state.myInfo.id,
      param,
      params
    );
  } catch (error) {
    var tempObject = {};
    tempObject.success = "false";
    tempObject.msg = "失败";
    result = JSON.stringify(tempObject);
  }
  return result;
};

Vue.prototype.$shellSQLIST = function(params) {
  let param = "OperatingBySqlList";
  let result = window.external.InvokeWinFormMethod(
    "UMP.Plugin.SqlLiteOpera",
    "SqlListData",
    store.state.myInfo.id,
    param,
    params
  );
  return result;
};

Vue.prototype.$loginInfo = function(params, next) {
  let param = arguments[1] ? "SearchBySqlstr" : "OperatingBySqlstr";
  let result = window.external.InvokeWinFormMethod(
    "UMP.Plugin.SqlLiteOpera",
    "SqlListData",
    "",
    param,
    params
  );
  return result;
};

//判断发送文件是否大于500M
Vue.prototype.$fileBigChoice = function(msg) {
  for (let i in msg) {
    if ((msg[i].FileSize || msg[i].FileLength) > 1024 * 1024 * 1024 * 4) {
      msg.splice(i, 1);
      this.$Message.warning("文件超过最大限制4G");
    }
  }
  return msg;
};

// 2022/4/21 zc修改加载（停止加载时关闭所有加载界面）
let loading;
let loadFlag;
let loadArr = [];
Vue.prototype.$startLoading = function(id) {
  loading = Vue.prototype.$loading({
    lock: true,
    text: "努力加载中...",
    background: "rgba(0,0,0,0.4)",
    target: document.querySelector(id ? id : ".loading-area") // 设置加载动画区域
  });
  if (loadFlag) {
    window.clearTimeout(loadFlag);
    loadFlag = null;
  }
  loadFlag = setTimeout(() => {
    loading.close();
  }, 5000);
  loadArr.push(loading);
  console.log(loadArr);
  return loadArr;
};

// 2022/4/21 zc修改加载（停止加载时关闭所有加载界面）
Vue.prototype.$endLoading = function() {
  console.log(loadArr);
  loadArr.forEach(l => {
    l.close();
  });
};

Vue.prototype.$func = {
  md5: function(str) {
    const md5 = crypto.createHash("md5");
    md5.update(str);
    return md5.digest("hex");
  },
  uuid: function() {
    var val = "";
    var str = store.state.uuid;
    for (var i = 0; i < str.length; i++) {
      val += "" + str[i].charCodeAt();
    }
    val = parseInt(val)
      .toString(16)
      .toUpperCase();
    val +=
      "-" +
      new Date()
        .getTime()
        .toString(16)
        .toUpperCase();
    for (let t = 0; t < 3; t++) {
      var msg = "";
      for (let i = 0; i < 6; i++) {
        msg += parseInt(Math.random() * 10);
      }
      val +=
        "-" +
        parseInt(msg)
          .toString(16)
          .toUpperCase();
    }
    return val;
  }
};
// 当前时间 时分秒
Vue.prototype.$getingTime = function() {
  let time = new Date();
  let hours = time.getHours() >= 10 ? time.getHours() : "0" + time.getHours();
  let minutes =
    time.getMinutes() >= 10 ? time.getMinutes() : "0" + time.getMinutes();
  let seconds =
    time.getSeconds() >= 10 ? time.getSeconds() : "0" + time.getSeconds();
  return hours + ":" + minutes + ":" + seconds;
};
// 时间戳初始化：服务于提醒时间
Vue.prototype.$newDateGetTime = function(date) {
  return date
    ? parseInt(new Date(date).getTime() / 1000)
    : parseInt(new Date().getTime() / 1000);
};
//判断字符串是否为null，空字符串
Vue.prototype.$isNull = function(str) {
  if (
    str == null ||
    str == "null" ||
    str == undefined ||
    str == "undefined" ||
    str == "" ||
    str.trim() == "" ||
    str == 0
  ) {
    return true;
  } else {
    return false;
  }
};
//排序
Vue.prototype.$personStatusSort = function(property) {
  if (property == "online") {
    return function(a, b) {
      var value1 = a[property];
      var value2 = b[property];
      return value2 - value1;
    };
  } else if (property == "CREATEDATE") {
    return function(a, b) {
      var value1 = new Date(a[property]).getTime();
      var value2 = new Date(b[property]).getTime();
      return value2 - value1;
    };
  } else {
    return function(a, b) {
      var value1 = a[property];
      var value2 = b[property];
      return value1 - value2;
    };
  }
};
/**
 * 字节大小转换为人类易读的B、KB、MB、GB、TB、PB单位
 * @param fileSize
 * @returns {string} 如3MB
 */
Vue.prototype.$formatSize = function(fileSize) {
  const arrUnit = ["B", "K", "M", "G", "T", "P"];
  let powerIndex = Math.log2(fileSize) / 10;
  powerIndex = Math.floor(powerIndex);
  // index should in the unit range!
  const len = arrUnit.length;
  powerIndex = powerIndex < len ? powerIndex : len - 1;
  let sizeFormatted = fileSize / Math.pow(2, powerIndex * 10);
  sizeFormatted = sizeFormatted.toFixed(2);
  return sizeFormatted + "" + arrUnit[powerIndex];
};
// date类型时间转换
Vue.prototype.$formatDateTime = function(dates, flag = false) {
  let year = dates.getFullYear();
  let month =
    dates.getMonth() + 1 >= 10
      ? dates.getMonth() + 1
      : "0" + (dates.getMonth() + 1);
  let date = dates.getDate() < 10 ? `0${dates.getDate()}` : dates.getDate();
  let hour = dates.getHours() < 10 ? `0${dates.getHours()}` : dates.getHours();
  let minutes =
    dates.getMinutes() < 10 ? `0${dates.getMinutes()}` : dates.getMinutes();
  let second =
    dates.getSeconds() < 10 ? `0${dates.getSeconds()}` : dates.getSeconds();
  if (flag) {
    return `${year}-${month}-${date}`;
  } else {
    return `${year}-${month}-${date} ${hour}:${minutes}:${second}`;
  }
};
//群组排序
Vue.prototype.$groupSort = function() {
  let groupOWner = this.group_detail.users.filter(item => item.POSITION == 1);
  let adminArr = this.group_detail.users
    .filter(item => item.POSITION == 2)
    .sort(this.$personStatusSort("online"));
  let statusArr = this.group_detail.users
    .filter(item => item.POSITION == 3)
    .sort(this.$personStatusSort("online"));
  this.group_detail.users = [];
  this.group_detail.users = [...groupOWner, ...adminArr, ...statusArr];
  console.log(this.group_detail.users, "排序之后的群用户");
};
//zk新增，中央事件总线
Vue.prototype.$bus = new Vue();

//截取字体长度
Vue.filter("ellipsis", function(value, num) {
  if (!value) return "";
  if (value.length > num) {
    return value.slice(0, num) + "...";
  }
  return value;
});
Vue.filter("setTime", function(date) {
  if (date) {
    var dateOld = Number(date);
    // 当前时间
    let nYear = new Date().getFullYear();
    let nMonth = new Date().getMonth() + 1;
    let nDay = new Date().getDate();
    // 传递过来的年月日
    let time = new Date(dateOld);
    let year = time.getFullYear();
    let month = time.getMonth() + 1;
    let hours = time.getHours();
    let minutes = time.getMinutes();
    let day = time.getDate();
    if (year < nYear) {
      return year + "年" + month + "月" + day + "日";
    } else if (month != nMonth || day != nDay) {
      return month + "月" + day + "日";
    } else {
      if (minutes < 10) {
        minutes = "0" + minutes;
      }
      return hours + ":" + minutes;
    }
  } else {
    return;
  }
});
Vue.filter("broadTime", function(date) {
  if (date) {
    var dateOld = Number(date);
    // 当前时间
    let nYear = new Date().getFullYear();
    let nMonth = new Date().getMonth() + 1;
    let nDay = new Date().getDate();
    // 传递过来的年月日
    let time = new Date(dateOld);
    let year = time.getFullYear();
    let month = time.getMonth() + 1;
    let hours = time.getHours();
    let minutes = time.getMinutes();
    let day = time.getDate();
    if (year < nYear) {
      return (
        year + "年" + month + "月" + day + "日" + "  " + hours + ":" + minutes
      );
    } else {
      if (minutes < 10) {
        minutes = "0" + minutes;
      }
      return month + "月" + day + "日" + "  " + hours + ":" + minutes;
    }
  } else {
    return;
  }
});
Vue.filter("timeFormat", function(date) {
  if (date) {
    var dateOld = Number(date);
    // 当前时间
    let nYear = new Date().getFullYear();
    let nMonth = new Date().getMonth() + 1;
    let nDay = new Date().getDate();
    // 传递过来的年月日
    let time = new Date(dateOld);
    let year = time.getFullYear();
    let month = time.getMonth() + 1;
    let hours = time.getHours();
    let minutes = time.getMinutes();
    let day = time.getDate();
    if (year < nYear) {
      if (minutes < 10) {
        minutes = "0" + minutes;
      }
      return (
        year + "年" + month + "月" + day + "日" + "  " + hours + ":" + minutes
      );
    } else if (month != nMonth || day != nDay) {
      if (minutes < 10) {
        minutes = "0" + minutes;
      }
      return month + "月" + day + "日" + "  " + hours + ":" + minutes;
    } else {
      if (minutes < 10) {
        minutes = "0" + minutes;
      }
      return hours + ":" + minutes;
    }
  } else {
    return;
  }
});
// 当前时间 年月日时分秒
Vue.filter("getTimeAll", function(date) {
  let time = new Date(parseInt(date));
  let year = time.getFullYear();
  let month =
    time.getMonth() + 1 >= 10
      ? time.getMonth() + 1
      : "0" + (time.getMonth() + 1);
  let day = time.getDate() >= 10 ? time.getDate() : "0" + time.getDate();
  let hours = time.getHours() >= 10 ? time.getHours() : "0" + time.getHours();
  let minutes =
    time.getMinutes() >= 10 ? time.getMinutes() : "0" + time.getMinutes();
  let seconds =
    time.getSeconds() >= 10 ? time.getSeconds() : "0" + time.getSeconds();
  return (
    year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds
  );
});

Vue.config.productionTip = false;

/* eslint-disable no-new */
const vm = new Vue({
  el: "#app",
  router,
  store,
  components: {
    App
  },
  template: "<App/>"
});

window.WriteConsole = function(info) {
  console.log(info, "console");
};
window.ActivateMainForm = function() {
  // 激活窗体
  // window.external.InvokeWinFormMethod("Internal.Function","ActivateMainForm");
};
window.emithot = function(info) {
  let req = JSON.parse(info);
  store.state.copyImg = req;
  console.log(store.state.copyImg);
};

window.InternalFunction = function(info) {
  console.log(info, "闪烁调用 参数--->");
};

Vue.directive("drag", function(el) {
  let odiv = el; //当前元素
  odiv.onmousedown = e => {
    //算出鼠标相对元素的位置
    let disX = e.clientX - odiv.offsetLeft;
    let disY = e.clientY - odiv.offsetTop;
    document.onmousemove = e => {
      e.stopPropagation();
      //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
      let left = e.clientX - disX + 230;
      let top = e.clientY - disY + 120;
      if (left <= 230) {
        left = 230;
      }
      if (top <= 250) {
        top = 250;
      }
      if (top >= document.body.clientHeight) {
        top = document.body.clientHeight;
      }
      if (left + 240 >= document.body.clientWidth) {
        left = document.body.clientWidth - 240;
      }
      //移动当前元素
      odiv.style.left = left + "px";
      odiv.style.top = top + "px";
    };
    document.onmouseup = e => {
      document.onmousemove = null;
      document.onmouseup = null;
    };
  };
});

Vue.prototype.$keyCodeName = function(e) {
  var keyName;
  console.log(e.keyCode);
  switch (e.keyCode) {
    case 8:
      keyName = "回退";
      break;
    case 9:
      keyName = "Tab";
      break;
    case 13:
      keyName = "Enter";
      break;
    case 16:
      keyName = "Shift";
      break;
    case 17:
      keyName = "Ctrl";
      break;
    case 18:
      keyName = "Alt";
      break;
    case 19:
      keyName = "PauseBreak";
      break;
    case 20:
      keyName = "Caps Lock";
      break;
    case 27:
      keyName = "Esc";
      break;
    case 32:
      keyName = "空格";
      break;
    case 33:
      keyName = "PageUp";
      break;
    case 34:
      keyName = "PageDown";
      break;
    case 35:
      keyName = "End";
      break;
    case 36:
      keyName = "Home";
      break;
    case 37:
      keyName = "方向键左";
      break;
    case 38:
      keyName = "方向键上";
      break;
    case 39:
      keyName = "方向键右";
      break;
    case 40:
      keyName = "方向键下";
      break;
    case 45:
      keyName = "Insert";
      break;
    case 46:
      keyName = "Delete";
      break;
    case 91:
      keyName = "左Win";
      break;
    case 92:
      keyName = "右Win";
      break;
    case 93:
      keyName = "快捷菜单键";
      break;
    case 95:
      keyName = "Sleep";
      break;
    case 96:
      keyName = "小键盘区0";
      break;
    case 97:
      keyName = "小键盘区1";
      break;
    case 98:
      keyName = "小键盘区2";
      break;
    case 99:
      keyName = "小键盘区3";
      break;
    case 100:
      keyName = "小键盘区4";
      break;
    case 101:
      keyName = "小键盘区5";
      break;
    case 102:
      keyName = "小键盘区6";
      break;
    case 103:
      keyName = "小键盘区7";
      break;
    case 104:
      keyName = "小键盘区8";
      break;
    case 105:
      keyName = "小键盘区9";
      break;
    case 106:
      keyName = "*";
      break;
    case 107:
      keyName = "+";
      break;
    case 109:
      keyName = "-";
      break;
    case 110:
      keyName = ".";
      break;
    case 111:
      keyName = "/";
      break;
    case 112:
      keyName = "F1";
      break;
    case 113:
      keyName = "F2";
      break;
    case 114:
      keyName = "F3";
      break;
    case 115:
      keyName = "F4";
      break;
    case 116:
      keyName = "F5";
      break;
    case 117:
      keyName = "F6";
      break;
    case 118:
      keyName = "F7";
      break;
    case 119:
      keyName = "F8";
      break;
    case 120:
      keyName = "F9";
      break;
    case 121:
      keyName = "F10";
      break;
    case 122:
      keyName = "F11";
      break;
    case 123:
      keyName = "F12";
      break;
    case 144:
      keyName = "NumLock";
      break;
    case 145:
      keyName = "ScrollLock";
      break;
    case 186:
      keyName = ";";
      break;
    case 187:
      keyName = "=";
      break;
    case 188:
      keyName = ",";
      break;
    case 189:
      keyName = "-";
      break;
    case 190:
      keyName = ".";
      break;
    case 191:
      keyName = "/";
      break;
    case 192:
      keyName = "`";
      break;
    case 219:
      keyName = "[";
      break;
    case 220:
      keyName = "\\";
      break;
    case 221:
      keyName = "]";
      break;
    case 222:
      keyName = "[']";
      break;
    case 255:
      keyName = "Wake";
      break;
    default:
      keyName = String.fromCharCode(e.keyCode);
      break;
  }
  if (e.shiftKey && e.keyCode != 16) {
    keyName = "Shift+" + keyName;
  }
  if (e.altKey && e.keyCode != 18) {
    keyName = "Alt+" + keyName;
  }
  if (e.ctrlKey && e.keyCode != 17) {
    keyName = "Ctrl+" + keyName;
  }
  return keyName;
};
//文件大小显示
Vue.filter("convertByte", function(byteCount) {
  var count = parseFloat(byteCount || 0),
    unitArr = ["b", "Kb", "Mb", "Gb", "Tb"],
    index = 0;
  if (!count) return 0;
  for (let i = 0; i < 5; i++) {
    if (count >= 1024) {
      count = count / 1024;
      index++;
    } else {
      return index > 0
        ? count.toFixed(2) + unitArr[index]
        : count + unitArr[index];
    }
    if (index == 4) {
      return count.toFixed(2) + unitArr[index];
    }
  }
});
//zk120新增，针对搜索结果跳聊天
Vue.prototype.$searchMdbTochat = function(item) {
  this.searchResultShow = false;
  if (item.isGroup == 1) {
    this.dbtoNewChat(item, true);
  } else {
    this.dbtoNewChat(item, false);
  }
};
//获取节点人员
Vue.prototype.$getGroupPeopleFn = function(FidArr, success) {
  this.$ajax(
    "user/getGroupPeople.do",
    {
      // 0 个人 1 部门节点
      fid: JSON.stringify(FidArr)
    },
    success,
    res => {
      console.log(res, "err=>");
    }
  );
};
Vue.prototype.$setWs = function(WebSockectUrl, deviceno) {
  return axios.post(WebSockectUrl, {
    deviceno: deviceno
  });
};
//index --->1为搜索,其他不需要参数
Vue.prototype.$operationalDatabase = function(statements, index) {
  let to = JSON.stringify({
    Sqlstr: statements
  });
  return arguments[1]
    ? JSON.parse(this.$shellSQL(to, index))
    : JSON.parse(this.$shellSQL(to));
};

Vue.prototype.$savePicture = function(item, myInfo, tableName) {
  //zk修改，下载原图
  this.$emit("chatFunctionHandle", false);
  let tempPic = "";
  let _this = this;
  //zk修改，下载原图rawvalue
  this.$downLoad(
    "api/v1/oim/image/download.do",
    item.DownLoadId,
    wt => {
      var fileReader = new FileReader();
      fileReader.onload = function(w) {
        let base64 = w.target.result.replace(/^data\:.{1,40}base64\,/gi, "");
        let arr = item.value.split(".").splice(-1)[0]; //获取后缀
        let info = _this.$shell("SaveFileStreamczs", [
          myInfo.id,
          item.DownLoadId,
          arr,
          base64,
          0
        ]);
        info = JSON.parse(info);
        tempPic = info.return_msg;
        //smallvalue写入数据库
        let ss = _this.$operationalDatabase(
          `UPDATE ${tableName} SET rawValue='${tempPic}' WHERE messageId='${
            item.messageId
          }';`
        );

        let path = _this.$utilJs.path_replace(tempPic); //zk修改item.value替换为tempPic，异步，提到上面
        console.log(path, item, "图片");
        let name = path.split("\\");
        console.log(name[name.length - 1], "图片名称");
        _this.$shell("SaveAS", [
          _this.$isRelativePath(path),
          name[name.length - 1]
        ]);
      };
      fileReader.readAsDataURL(wt);
    },
    wt => {
      console.log("error");
      console.log(wt);
    }
  );
};
//改变头部颜色
Vue.prototype.$changeTitleColor = function(a, b) {
  this.$shell("DrawTitleColor", ["#e67529", a, b]);
};
//拼接相对路径
Vue.prototype.$isRelativePath = function(e) {
  if (!e || e.indexOf(":") > 0) {
    //如果是之前保存的绝对路径
    return e;
  } else {
    //console.log('相对路径',store.state.defultPath+e)
    return store.state.defultPath + e;
  }
};

Vue.prototype.$date = function(e, format) {
  return new Date(e).dateFormat(format);
};

// 格式化时间 new Date().dateFormat("yyyy-MM-dd hh:mm")
Date.prototype.dateFormat = function(format) {
  var o = {
    "M+": this.getMonth() + 1, //month
    "d+": this.getDate(), //day
    "h+": this.getHours(), //hour
    "m+": this.getMinutes(), //minute
    "s+": this.getSeconds(), //second
    "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
    S: this.getMilliseconds() //millisecond
  };
  if (/(y+)/.test(format)) {
    format = format.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return format;
};

//头像下载地址
Vue.prototype.$get_inline_head = function(id) {
  return store.state.url + store.state.imgDownLoadUrl + id;
};
